package jzqb.annotation.loginlog;


import haha.life.normal.FastJsonUtils;
import jzqb.common.Result;
import jzqb.po.AdminLoginLogPo;
import jzqb.po.AdminLoginPo;
import jzqb.service.AdminUserInfoService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

@Aspect
@Component
public class LoginLogAspect {

    @Autowired
    AdminUserInfoService adminuserinfoservice;

    //定义切点
    @Pointcut("@annotation(jzqb.annotation.loginlog.LoginLog)")//注意这个写类的全路径
    public void logPoint(){

    }

    @Before("logPoint()")
    public void beforePoint(JoinPoint joinPoint){
    }

    //切点后执行
    @After("logPoint()")
    public void afterPoint(){

    }

    @Around("logPoint()")
    public Object  around(ProceedingJoinPoint pjp) throws Throwable {
        return pjp.proceed();
    }

    /**
     * 用户成功登录后才会记录登录记录
     * @param ret 返回的结果:Result类型
     * @throws Throwable 异常
     */
    @AfterReturning(returning = "ret",pointcut="logPoint()")
    public void saveLog(Result ret) throws Throwable {
        if (ret.getCode() == 200){
            AdminLoginPo login=  FastJsonUtils.getJsonToBean(((HashMap) ret.getData()).get("userinfo").toString(),AdminLoginPo.class);
            String id = login.getId();
            String name = login.getName();
            HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String ipAddress = req.getRemoteAddr();
            AdminLoginLogPo adminLoginLogPo = new AdminLoginLogPo();
            adminLoginLogPo.setUserid(id);
            adminLoginLogPo.setUserName(name);
            adminLoginLogPo.setIPaddress(ipAddress);
            adminLoginLogPo.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            adminuserinfoservice.insertLoginRecord(adminLoginLogPo);
        }
    }
}
